package edu.nwpu.zya.coreops.modules.monitor.service.impl;

import com.alibaba.fastjson.JSONObject;
import edu.nwpu.zya.coreops.common.utils.DateUtils;
import edu.nwpu.zya.coreops.config.ElasticSearchConfig;
import edu.nwpu.zya.coreops.modules.monitor.vo.RdsMonitorVo;
import edu.nwpu.zya.coreops.modules.monitor.service.RdsMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("rdsMonitorService")
public class RdsMonitorServiceImpl implements RdsMonitorService {
    @Qualifier("esRestClient")
    @Autowired
    private RestHighLevelClient esRestClient;

    /**
     * 获取RDS监控指标series
     * @param instanceId 实例id
     * @param timePeriod 聚合时间段
     * @return
     */
    @Override
    public List<RdsMonitorVo> getSeriesByIdAndPeriod(String instanceId, Integer timePeriod) {
        List<RdsMonitorVo> series=new ArrayList<RdsMonitorVo>();
        // 从elasticsearch查询对应ECS实例的数据
        SearchRequest searchRequest = new SearchRequest("rds");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(timePeriod*4).sort("time", SortOrder.ASC);
        Date now=new Date();
        Date from= DateUtils.addDateMinutes(now,0-timePeriod);
        searchSourceBuilder.query(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("instanceId",instanceId)).filter(QueryBuilders.rangeQuery("time").gte(from).lte(now)));
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse=null;
        try {
            searchResponse= esRestClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            log.error("rds实例{}，查询数据失败",instanceId);
            e.printStackTrace();
        }
        if(searchResponse!=null){
            SearchHits searchHits = searchResponse.getHits();
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit :
                    hits) {
                String source = hit.getSourceAsString();

                RdsMonitorVo rdsMonitorVo = JSONObject.parseObject(source, RdsMonitorVo.class);
                series.add(rdsMonitorVo);
            }
        }

        return series;
    }
}
